export function mCall(event, data = '', callback) {
	return new Promise((resolve, reject) => {
		if (typeof data === 'object') {
			data = JSON.stringify(data)
		}
		
		// 小程序
		if (uni.sendNativeEvent) {
			uni.sendNativeEvent(event, data);
		} else { // h5
			console.log('event:', event)
			if (window.PKFunJS && window.PKFunJS[event]) {
				console.log('PKFunJS:', window.PKFunJS)
				resolve(window.PKFunJS[event](data))
			}
		}
		
	})
}

export function mBus(callbacks = {}) {
	const events = Object.keys(callbacks)

	// 小程序
	if (uni.sendNativeEvent) {
		uni.onNativeEventReceive((event = '', data = {}) => {
		  mCall('log', {msg: `===========${event}: ${JSON.stringify(data)}`});
			if(!!~events.indexOf(event)){
				try{
					const resData = data && typeof data === 'string' ? JSON.parse(data) : (data || {});
					callbacks[event] && callbacks[event](resData || '')
				}catch(e){
					mCall('log', {msg: `----------${event} error: ${JSON.stringify(e)}`});
				}
				
			}
		});
	} else { // h5
		window.PKFunEvent = (event, data) => {
			if(!!~events.indexOf(event)){
				// if (!/Scan/.test(event)) console.log('PKFunEvent----=' + event + '----=' + JSON.stringify(data));
				try{
					const resData = data && typeof data === 'string' ? JSON.parse(data) : (data || {});
					callbacks[event] && callbacks[event](resData || '')
				}catch(e){
					mCall('log', {msg: `----------${event} error: ${JSON.stringify(e)}`});
				}
			}
		}
	}
}